﻿using Microsoft.ExtendedReflection.ComponentModel;
using Microsoft.ExtendedReflection.Monitoring;
using Microsoft.ExtendedReflection.Remote;
using MolesVS2012.Host;
using System.Runtime.Remoting.Channels;

namespace MolesVS2012.Host.Host
{
    internal class MolesHostRemotingManager : ComponentBase, IService
    {
        private string serverChannel;
        private string clientID;
        private IChannel _channel;

        public bool Connected
        {
            get
            {
                return this._channel != null;
            }
        }

        public string ServerChannel
        {
            get
            {
                return this.serverChannel;
            }
        }

        protected override void Initialize()
        {
            base.Initialize();
            this.serverChannel = MolesVsHostEnvironmentSettings.ServerChannel.Value;
            this.clientID = MolesVsHostEnvironmentSettings.ClientID.Value;
            this.Log.LogMessage("channel: {0}", this.serverChannel);
            this.Log.LogMessage("clientid: {0}", this.clientID);
            using (_ProtectingThreadContext.Acquire())
            {
                if (RemoteClient.TryRegisterServer(this.serverChannel, this.clientID, (IServiceProvider)this.Site, out this._channel))
                    return;
                this.Log.LogError("Missing Wiki Topic", "Host", "failed to register client over channel {0}", new object[1]
        {
          (object) this.serverChannel
        });
            }
        }

        public bool Ping()
        {
            if (this.Connected)
            {
                using (_ProtectingThreadContext.Acquire())
                    RemoteServer.GetConnector(this.serverChannel).Ping();
            }
            return true;
        }

        public bool TrySetClientReady()
        {
            if (!this.Connected)
                return false;
            using (_ProtectingThreadContext.Acquire())
                RemoteServer.GetConnector(this.serverChannel).ClientReady(this.clientID);
            return true;
        }

        public bool WaitTillFinished()
        {
            using (_ProtectingThreadContext.Acquire())
                return RemoteServer.GetConnector(this.serverChannel).WaitUntilReady(this.clientID);
        }

        public override void Dispose()
        {
            base.Dispose();
            IChannel channel = this._channel;
            if (channel == null)
                return;
            this._channel = (IChannel)null;
            using (_ProtectingThreadContext.Acquire())
                RemoteServer.UnregisterServer(channel);
        }
    }
}

